<template>
    <div class="container">
        <el-scrollbar ref="refScrollbar" @wheel.prevent="handleScroll">
            <div class="nav">
                <el-row>
                    <el-input v-model="searchShopName" placeholder="输入商品名称 " />
                    <el-input v-model="searchBarCode" placeholder="输入商品条形码 " />
                    <el-select v-model="searchStatus" placeholder="请选择商品状态">
                        <el-option v-for="item in shopStatysMap" :key="item.value" :label="item.name" :value="item.value" />
                    </el-select>
                    <el-cascader placeholder="请选择类目"
                        :props="{ emitPath: false, value: 'id', children: 'childrenList', label: 'title' }"
                        v-model="searchCategory" :options="cascaderCategoryData" @change="handleChange" />
                    <el-button type="primary" icon="Search" @click="search()">查找</el-button>
                    <el-button v-power="'product:product:create'" type="primary" icon="Plus" @click="handleCreate()">添加</el-button>
                </el-row>
            </div>
        </el-scrollbar>

        <div class="table">
            <el-table ref="multipleTableRef" border :data="tableData" max-height="700" style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column type="expand" label="sku信息" width="55" align="center">
                    <template #default="props">
                        <div>
                            <el-table :data="props.row.skuList" max-height="300" border>
                                <el-table-column label="商品条码" prop="barCode" width="200" align="center" />
                                <el-table-column label="商品规格" prop="title" width="200" align="center" />
                                <el-table-column label="商品库存" prop="stock" width="200" align="center" />
                                <el-table-column label="原价" align="center" width="200">
                                    <template #default="scope">
                                        {{ scope.row.originalPrice / 100 }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="现价" prop="address" align="center" width="200">
                                    <template #default="scope">
                                        {{ scope.row.price / 100 }}
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="id" label="商品Id" width="120" align="center" />
                <el-table-column prop="title" label="名称" width="250" align="center" />
                <el-table-column label="图片" width="100" align="center">
                    <template #default="scope">
                        <div class="pic">
                            <img :src="scope.row.img" alt="">
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="name" label="商品详细介绍" width="120" align="center">
                    <template #default="scope">
                        <el-button size="small" type="primary" @click="lookDetail(scope.row.id)">查看</el-button>
                    </template>
                </el-table-column>
                <el-table-column prop="categoryId" label="类目Id" width="120" align="center" />
                <el-table-column prop="freightTemplateId" label="邮费模板Id" width="120" align="center" />
                <el-table-column prop="sales" label="销量" width="120" align="center" />
                <el-table-column prop="unit" label="单位" width="120" align="center" />
                <el-table-column prop="status" label="是否在售" width="120" align="center">
                    <template #default="scope">
                        <el-tag :type="scope.row.status ? 'success' : 'danger'">{{ scope.row.status ? '在售' : '下架'
                        }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="description" label="描述" width="200" show-overflow-tooltip align="center" />
                <el-table-column fixed="right" label="操作" width="170" align="center">
                    <template #default="scope">
                        <el-button size="small"  v-power="'product:product:edit'"  type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
                        <el-button size="small" :type="scope.row.status ? 'success' : 'warning'"
                            @click="throttledChangShelves(scope.row.id, scope.row.status)">{{ scope.row.status ? '下架' : '上架'
                            }}</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div class="Pagination">
            <Pagination :data="pagination" @setlm="getlm" @setpg="getpg"></Pagination>
        </div>
        <div class="detail">
            <el-dialog v-model="dialogDetail" :title="title" align-center>
                <div class="detail-image" v-html="detailImg" style="text-align: center;"></div>
            </el-dialog>

        </div>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import Pagination from '../../components/Pagination/Pagination.vue'//分页组件
import { type IBackStatus } from '#/index'
import { ElMessage } from 'element-plus/lib/components/index.js';
import { ElTable } from 'element-plus'
import { get } from '@/utils/https'
import { useRouter } from 'vue-router'
const router = useRouter()
const dialogDetail = ref(false)
const title = ref('')
let detailImg = ref('')//详情
let tableData: TypeAdver[] = reactive([])
let cascaderCategoryData: TypeSpuBigTree[] = reactive([])

let pages = computed(() => Math.ceil(pagination.count / pagination.limit))
let pagination = reactive({
    page: 1,
    limit: 10,
    count: 0
})

// 多选
interface User {
    date: string
    name: string
    address: string
}
let searchShopName = ref('')
let searchBarCode = ref('')
let searchStatus = ref('')
let searchCategory = ref('')


const multipleTableRef = ref<InstanceType<typeof ElTable>>()
const multipleSelection = ref<User[]>([])
const handleSelectionChange = (val: User[]) => {
    multipleSelection.value = val
    console.log(123, val);
}

const handleChange = (value: any) => {
    // console.log(value)
    console.log(searchCategory.value, 'searchCategory');

}
// 广告状态
const shopStatysMap = reactive([
    { value: 1, name: "在售" },
    { value: 0, name: "下架" }
]);

/**
 * @handleCreate 添加
 * 
 */
const handleCreate = () => {
    router.push('/index/shop/create');
}
/**
 * @handleEdit 编辑
 * 
 */
const handleEdit = (id: number) => {
    // console.log(id,'id');
    let routers = `/index/shop/edit/${id}`
    router.push(routers);
}
/**
 * @search 查找
 */
function search() {
    getInit()
}
/**
 * @lookDetail 查看
 */
function lookDetail(id: number) {
    title.value = "详情"
    let data = {
        _gp: 'admin.product',
        _mt: 'detail',
        spuId: id,
    }
    get(data).then((res: any) => {
        console.log('商品详情', res)
        let { errno, data } = res
        if (200 == errno) {
            detailImg.value = data.detail
        }
    })
    dialogDetail.value = true
}

/**
 * @changeStatus 上下架
 */
let timer: ReturnType<typeof setTimeout> | undefined;

function changShelvesThrottled(id: number, status: number) {
    if (timer === undefined) {
        // 第一次直接执行
        changeStatus(id, status);
        timer = setTimeout(() => {
            timer = undefined;
        }, 1000);
    } else {
        // 先清空定时器，再设置新的定时器
        clearTimeout(timer);
        timer = setTimeout(() => {
            changeStatus(id, status);
            timer = undefined;
        }, 1000);
    }
}

const throttledChangShelves = changShelvesThrottled;
const changeStatus = (id: number, status: number) => {
    let action = ''
    if (status == 0) {
        status = 1
        action = '上架'
    } else {
        status = 0
        action = '下架'
    }
    let data = {
        _gp: 'admin.product',
        _mt: 'freezeOrActivation',
        spuId: id,
        status: status
    }
    // console.log(data, 'data');
    get(data).then((res: any) => {
        // console.log('上下架', res)
        let { errno, errmsg } = res
        if (200 == errno) {
            getInit()
            ElMessage.success(action + errmsg)
        } else {
            ElMessage.error(errmsg)
        }
    })
}
/**
 * 分页自定义事件
 */
const getlm = (v: IBackStatus) => {
    pagination.limit = v.backStatus
}
const getpg = (v: IBackStatus) => {
    pagination.page = v.backStatus
}

// 解决分页请求两次问题
watch([() => pagination.limit, () => pagination.page], (values, oldValues) => {
    if (pagination.page <= pages.value) {
        console.log(213);
        getInit()
    }
})

/**
 * 滚动事件
 *scrollbar.wrap$获取到包裹容器的element对象
 */
const refScrollbar = ref();
const handleScroll = (e: { wheelDelta: number; deltaY: number }) => {
    const wheelDelta = e.wheelDelta;
    const scrollbar = refScrollbar.value;
    scrollbar.setScrollLeft(scrollbar.wrapRef.scrollLeft - wheelDelta);
};
// 获取初始化数据
let getInit = () => {
    let data = {
        _gp: 'admin.product',
        _mt: 'list',
        page: pagination.page,
        limit: pagination.limit,
        categoryId: searchCategory.value,
        barcode: searchBarCode.value,
        status: searchStatus.value,
        title: searchShopName.value,
        adminId: null
    }
    // console.log(data, 'data');
    get(data).then((res: any) => {
        console.log('商品列表获取数据成功', res)
        let { errno, data } = res
        if (200 == errno) {
            let { count, items } = data
            tableData.length = 0
            tableData.push(...items)
            pagination.count = count
        }
    })
    let categoryData = {
        _gp: 'admin.category',
        _mt: 'categoryTree',
    }
    get(categoryData).then((res: any) => {
        // console.log('类目获取数据成功', res)
        if (200 == res.errno) {
            cascaderCategoryData.length = 0
            cascaderCategoryData.push(...res.data)
        }
    })

}
onMounted(() => {
    getInit()
})
</script>


<style lang="less" scoped>
.el-input {
    width: 180px;
}
.el-row {
    margin-bottom: 10px;
    width: 1200px;
    height: 32px;
    // overflow: hidden;
    background-color: rgb(228, 182, 202);
}
.detail-image  /deep/img {
    width: 100%;
}
</style>
